package cn.com.heaton.bleLib.logic.command.impl;


import android.text.format.DateUtils;

import java.util.Calendar;

import cn.com.heaton.bleLib.ble.Ble;
import cn.com.heaton.bleLib.ble.L;
import cn.com.heaton.bleLib.ble.callback.BleWriteCallback;
import cn.com.heaton.bleLib.ble.model.BleDevice;
import cn.com.heaton.bleLib.logic.HexUtil;
import cn.com.heaton.bleLib.logic.command.Command;

/**
 * 同步系统时间给设备
 */
public class CmdSyncTime extends Command {

    private static final String TAG = "CmdSyncTime";
    private Ble<BleDevice> mBle;
    private BleDevice mDevice;
    private BleWriteCallback mCallBack;
    private byte[] mSendBuffer;

    public CmdSyncTime(Ble<BleDevice> ble, BleDevice device, BleWriteCallback callback) {
        mBle = ble;
        mDevice = device;
        mCallBack = callback;
        initData();
    }

    private void initData() {
        byte[] cmd = new byte[7];
        cmd[0] = Command.Cmd_Set_Time;

        Calendar now = Calendar.getInstance();

        int year = now.get(Calendar.YEAR) - 2000;
        cmd[1] = HexUtil.HexToByte(Integer.toHexString(year));

        int month = (now.get(Calendar.MONTH) + 1);
        cmd[2] = HexUtil.HexToByte(Integer.toHexString(month));

        int day = now.get(Calendar.DAY_OF_MONTH);
        cmd[3] = HexUtil.HexToByte(Integer.toHexString(day));
        int hour = now.get(Calendar.HOUR_OF_DAY);
        cmd[4] = HexUtil.HexToByte(Integer.toHexString(hour));
        int minute = now.get(Calendar.MINUTE);
        cmd[5] = HexUtil.HexToByte(Integer.toHexString(minute));
        int second = now.get(Calendar.SECOND);
        cmd[6] = HexUtil.HexToByte(Integer.toHexString(second));
        mSendBuffer = combineData(cmd, cmd.length);
    }

    @Override
    protected boolean execute() {
        L.i(TAG, "发送了一条获取设备时间指令");
        return mSendBuffer != null && mBle.write(mDevice, mSendBuffer, mCallBack);
    }
}
